namespace PHSRAG.Insight21.Humans
{
	using PHSRAG.Insight21.Context;
	using PHSRAG.Security.Enumerations;
	using System;
	using System.Data;
	using System.Drawing;
	using System.Web;
	using System.Web.UI.WebControls;
	using System.Web.UI.HtmlControls;
	using System.Collections;
    using DataAccess = PHSRAG.Utility.DataAccess;
    using Header = PHSRAG.Insight21.InsightWebControls.Header;

	/// <summary>
	///		Summary description for CreateNewProcessBar.
	/// </summary>
	public partial class CreateNewProcessBar : System.Web.UI.UserControl
	{
		#region Constants
		private const string RefCodeMeaningColumn = "Meaning";
		private const string RefCodeCodeColumn = "Code";
		#endregion

		#region Instance variables
		private Policy.ICachePolicy applicationCachePolicy;
		private Policy.ICachePolicy	pageCachePolicy;
		private Policy.ICachePolicy cachePolicy;
		private int protocolId;
		private int userAccessLevel;
      private Protocol protocol;

      public string ModuleName = string.Empty;
		#endregion

		#region Properties
		/// <summary>
		/// Sets the id of the protocol for which details will be displayed
		/// </summary>
		public int ProtocolID
		{
			set
			{
				protocolId = value;
			}
		}

		/// <summary>
		/// Sets the access level for the logged-in user
		/// </summary>
		public int UserAccessLevel
		{
			set
			{
				userAccessLevel = value;
			}
		}

        /// <summary>
        /// Gets the protocol .If it's not already in the cache, it loads it up based on the protocolId passed to the page, and caches the object
        /// </summary>
        private Protocol Protocol
        {
            get
            {
                string cacheKey = Protocol.ProtocolKey;
                protocol = cachePolicy.GetCachedObject(cacheKey) as Protocol;

                if ((protocol == null) || (protocolId != protocol.Id))
                {
                    protocol = new Protocol(cachePolicy);
                    protocol.Load(DataAccess.ConnectionString, protocolId);
                    cachePolicy.Cache(cacheKey, protocol);
                }
                return protocol;
            }
        }
        #endregion

		#region Page Events
		/// <summary>
		/// Attempts to retrieve a protocol from the cache.  If there, it compares it's ID to the
		/// one maintained, and checks the equality.  If they're different, it loads up a new protocol
		/// based on it, and caches it.  Otherwise, it uses the one in the cache.
		/// </summary>
		/// <param name="sender">Object that raised the event</param>
		/// <param name="e">Arguments associated with the event</param>
		protected void Page_Load(object sender, System.EventArgs e)
		{                    
            /* If the page has set a different protocolId for a protocol to load, 
            * it will be greater than 0.  If they differ, use the protocolId 
            * that the page has set to load the protocol*/
             if (protocolId == 0 || userAccessLevel == 0)
             {
                 throw new Exception(
                    "The page must set the id of the protocol and the user access level this control should display details for");
             }
             // get the protocol types from teh domain, and fill in the drop down with them.
             CDS.RefCodes refCodes = (CDS.RefCodes)applicationCachePolicy.GetCachedObject(CDS.RefCodes.CacheKey);

             string domain = (Protocol.ModuleType == Constants.ModuleType.Animals) ? Humans.Constants.AnimalProtocolProcessType.Domain : Humans.Constants.ProtocolProcessType.Domain;
             ArrayList processTypes = refCodes.GetRefCodes(domain);
             if (!IsPostBack)
             {
                 processType.Items.Add(new ListItem("<--Select a type-->", "0"));

                 for (int i = 0, j = processTypes.Count; i < j; ++i)
                 {
                     CDS.RefCode refCode = (CDS.RefCode)processTypes[i];
                     if (refCode.Code != Humans.Constants.ProtocolProcessType.InitialReview
                               && refCode.Code != Humans.Constants.AnimalProtocolProcessType.InitialReview)
                         processType.Items.Add(new ListItem(refCode.Meaning, refCode.Code));
                 }
             }
             string createProcessTogglerScript = string.Format("createProcessToggler('{0}', '{1}');", processType.ClientID, createProcess.ClientID);

             processType.Attributes.Add("onchange", createProcessTogglerScript);

             if (!Page.ClientScript.IsStartupScriptRegistered("CreateProcessTogglerScript"))
             {
                 Page.ClientScript.RegisterStartupScript(GetType(), "CreateProcessTogglerScript", string.Format("<Script>{0}</script>", createProcessTogglerScript));
             }             
                
		}
		#endregion

		#region Web Form Designer generated code
		/// <summary>
		/// Init event
		/// </summary>
		/// <param name="e">Arguments associated with the event.</param>
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
			applicationCachePolicy = (Policy.ICachePolicy)Application[Policy.Names.ApplicationCachePolicyKey];
			cachePolicy = (Policy.ICachePolicy)Session[Policy.Names.CachePolicyKey];
			pageCachePolicy = (Policy.ICachePolicy)Session[Policy.Names.PageCachePolicyKey];
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.createProcess.Click += new System.Web.UI.ImageClickEventHandler(OnCreateProcessClick);

		}
		#endregion

		private void OnCreateProcessClick(object sender, System.Web.UI.ImageClickEventArgs e)
		{
			// cache the selected value so the New App page knows which questionnaire to load.
			Hashtable outgoingData = new Hashtable();
			outgoingData.Add(Keys.ProtocolIdKey, protocolId);
			outgoingData.Add(Keys.ProtocolAccessKey, userAccessLevel);
			outgoingData.Add(Keys.NewProcessTypeKey, processType.SelectedValue);
			pageCachePolicy.Cache(Keys.IncomingDataKey, outgoingData);

			if ( processType.SelectedValue == Humans.Constants.ProtocolProcessType.ContinuingReview )
			{
				Page.Response.Redirect(
					Utility.Settings.GetKeyValue("SubModuleNavigation.Humans.ContinuingReviewSelectionPageURL",""));
			}
			else
			{
				Page.Response.Redirect(
					Utility.Settings.GetKeyValue("SubModuleNavigation.Humans.NewProcessPageURL",""));
			}
		}
	}
}
